package com.zz.parkingsystem.controller.admin;

import com.zz.parkingsystem.aop.LogAnnotation;
import com.zz.parkingsystem.dto.AdminDTO;
import com.zz.parkingsystem.dto.AdminLoginDTO;
import com.zz.parkingsystem.entity.Admin;
import com.zz.parkingsystem.entity.Dept;
import com.zz.parkingsystem.entity.SystemLogin;
import com.zz.parkingsystem.service.AdminService;
import com.zz.parkingsystem.service.DeptService;
import com.zz.parkingsystem.service.SystemLoginService;
import com.zz.parkingsystem.util.MD5Util;
import com.zz.parkingsystem.util.OssUtil;
import com.zz.parkingsystem.util.Result;
import com.zz.parkingsystem.util.ResultGenerator;
import com.zz.parkingsystem.vo.PageResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author wangyuxiang
 */
@Api(tags = "管理员请求")
@RestController
@RequestMapping("/admin")
public class AdminController {
    @Resource
    private AdminService adminService;
    @Resource
    private SystemLoginService systemLoginService;

    @Resource
    private DeptService deptService;

    @Resource
    private OssUtil ossUtil;

    @PostMapping("/regist")
    @ApiOperation(value = "管理员注册")
    @ApiParam(name = "admin实体类", value = "电话tel，密码，必传")
    public Result regist(@Validated @RequestBody Admin admin) {
        Admin admin1 = adminService.selAdminByTel(admin.getAdminTel());
        if (admin1 != null) {
            return ResultGenerator.genFailResult("此账号已被注册！");
        } else {
            return ResultGenerator.genSuccessResult(adminService.adminRegist(admin));
        }
    }


    @PostMapping("/login")
    @ApiOperation(value = "管理员登录")
    @ApiParam(name = "adminDTO实体类", value = "电话tel，密码，必传")
    public Result adminLogin(@RequestBody AdminLoginDTO admin, HttpServletRequest request) {
        //在会话中添加对象
        HttpSession session = request.getSession();

        if ("".equals(admin.getAdminTel())) {
            return ResultGenerator.genFailResult("请填写账号！");
        }

        if ("".equals(admin.getAdminPassword())) {
            return ResultGenerator.genFailResult("请填写密码！");
        }
        //先根据电话查询盐值，把盐值放到参数里
        Admin admin2 = adminService.selAdminByTel(admin.getAdminTel());
        admin.setAdminSalt(admin2.getAdminSalt());
        //执行登录查询
        Admin admin1 = adminService.adminLogin(admin);

        if (admin1 != null) {
            session.setAttribute("admin", admin1);
            //生成一条新的登录日志
            SystemLogin systemLogin = new SystemLogin();
            //请求开始时间
            systemLogin.setSlLoginTime(new Date());
            //请求ip地址获取
            String ip = request.getRemoteAddr();
            systemLogin.setSlIp(ip);
            //请求管理员昵称
            systemLogin.setSlLoginUser(admin1.getAdminNickname());
            systemLoginService.insertSelective(systemLogin);
            return ResultGenerator.genSuccessResult(admin1);
        } else {
            return ResultGenerator.genFailResult("用户名或密码错误！");
        }
    }


    @PostMapping("/updatePassword")
    @ApiOperation(value = "管理员修改密码")
    @ApiParam(name = "adminDTO实体类", value = "id,电话tel，密码，盐值,新密码,必传")
    @LogAnnotation(module = "管理员", operation = "修改密码")
    public Result adminUpdatePassword(@Validated @RequestBody AdminLoginDTO admin) {
        if (adminService.adminLogin(admin) == null) {
            return ResultGenerator.genFailResult("原始密码错误！");
        } else {
            String s = adminService.adminUpdatePassword(admin);
            return ResultGenerator.genSuccessResult(s);
        }
    }

    @GetMapping("/queryAllDept")
    @ApiOperation(value = "查询所有部门信息")
    @ApiParam(name = "查询所有部门信息", value = "无参数")
    public Result queryAllDept() {
        List<Dept> depts = deptService.queryAllDept();
        return ResultGenerator.genSuccessResult(depts);
    }

    @GetMapping("/selAdminById/{id}")
    @ApiOperation(value = "根据id查个人信息")
    @ApiParam(name = "根据id查个人信息", value = "用于修改之前的查询")
    public Result selAdminById(@PathVariable("id") String adminId) {
        Admin admin = adminService.selectByPrimaryKey(Long.parseLong(adminId));
        return ResultGenerator.genSuccessResult(admin);
    }

    @PutMapping("/updateAdmin")
    @ApiOperation(value = "根据id修改个人信息")
    @ApiParam(name = "根据id修改个人信息", value = "")
    @Transactional
    public Result updateAdmin(@RequestBody Admin admin) {
        int i = adminService.updateByPrimaryKeySelective(admin);
        if (i > 0) {
            return ResultGenerator.genSuccessResult("修改成功！");
        } else {
            return ResultGenerator.genFailResult("修改失败！");
        }
    }


    @PostMapping("/queryAllAdmin")
    @ApiOperation(value = "查询所有管理员信息")
    @ApiParam(name = "查询所有管理员信息", value = "srId")
    public Result queryAllAdmin(@RequestBody AdminDTO adminDTO) {
        PageResult pageResult = adminService.queryAllAdmin(adminDTO);
        return ResultGenerator.genSuccessResult(pageResult);
    }

    @DeleteMapping("/delete/{id}")
    @ApiOperation(value = "根据id删除管理员")
    @ApiParam(name = "根据id删除管理员", value = "adminId")
    public Result del(@PathVariable("id") Integer adminId) {
        int i = adminService.deleteByPrimaryKey(adminId.longValue());
        return ResultGenerator.genSuccessResult();
    }



    /**
     * 上传到阿里云
     */
    @PostMapping("/uploadoss")
    @ApiOperation(value = "上传头像到阿里云")
    @ApiParam(name = "file", value = "头像文件")
    public Result fileUpload(@RequestParam("file") MultipartFile file) {
        try {
            String url = ossUtil.uploadFile(file);
            return ResultGenerator.genSuccessResult(url);
        } catch (Exception e) {
            return ResultGenerator.genFailResult("上传失败");
        }
    }
    /**
     * 本地文件上传
     * @param file
     * @param request
     * @return
     */
    @PostMapping("upload")
    public Result upload(@RequestParam("file") MultipartFile file, HttpServletRequest request) {

        //获取文件在服务器的储存位置
        String path = request.getSession().getServletContext().getRealPath("/upload");
        File filePath = new File(path);
        if (!filePath.exists() && !filePath.isDirectory()) {
            filePath.mkdir();
        }

        //获取原始文件名称(包含格式)
        String originalFileName = file.getOriginalFilename();

        //获取文件类型，以最后一个`.`为标识
        String type = originalFileName.substring(originalFileName.lastIndexOf(".") + 1);

        //获取文件名称（不包含格式）
        String name = originalFileName.substring(0, originalFileName.lastIndexOf("."));

        //设置文件新名称: 当前时间+文件名称（不包含格式）
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String date = sdf.format(new Date());
        String fileName = date + name + "." + type;

        //在指定路径下创建一个文件
        File targetFile = new File(path, fileName);
        Result result = new Result();
        //将文件保存到服务器指定位置
        try {
            file.transferTo(targetFile);
            //将文件在服务器的存储路径返回
          return   ResultGenerator.genSuccessResult("http://localhost:9000/upload/" + fileName);

        } catch (IOException e) {
            e.printStackTrace();
            return  ResultGenerator.genFailResult("\"上传失败\"");
        }
    }

}
